#! /bin/sh
#
#  This script builds FreeRADIUS in a docker environment
#  using the Dockerfiles in this directory.
#
#  Example usage: ./dockerbuild build-debian9
#

set -eu

usage ()
{
	[ "0$1" -gt 0 ] && exec 1>&2
	echo "Syntax: $0 [options] <dir>"
	echo "  -c	disable docker cache"
	echo "  -j	build jenkins image instead of main image"
	echo "  -l	build with clang rather than gcc"
	echo "  -d	build with faster for dev only (smaller key sizes)"
	echo "  -s	build with alternative git source"
	echo "  -b	build with alternative git branch"
	echo "  -h	this help"
	exit $1
}

while getopts "chjlds:b:" OPT
do
	case $OPT in
	c)	OPT_NOCACHE=1;;
	j)	OPT_JENKINS=1;;
	l)	OPT_CC=clang;;
	d)	OPT_DEV=1;;
	s)	OPT_SOURCE="$OPTARG";;
	b)	OPT_BRANCH="$OPTARG";;
	h)	usage 0;;
	*)	usage 1;;
	esac
done
shift $(expr $OPTIND - 1)

DIR="$1"

[ -z "$DIR" ] && usage 1
[ ! -d "$DIR" ] && echo "Directory '$DIR' does not exist" && exit 1

#
#  Work out which OS to base our image on from the dir name
#
DIR=$(echo "$DIR" | sed -e 's/\/$//')
OSNAME=$(echo "$DIR" | sed -e 's/^build-//')

#
#  Build dependency image with compiler and all source ready to go
#
[ ! -r "$DIR/Dockerfile.deps" ] && echo "'$DIR/Dockerfile.deps' does not exist" && exit 1
echo Building $OSNAME source and dependency image
docker build \
	${OPT_NOCACHE:+--no-cache} \
	${OPT_SOURCE:+--build-arg=source=$OPT_SOURCE} \
	${OPT_BRANCH:+--build-arg=branch=$OPT_BRANCH} \
	-t freeradius/$OSNAME-deps \
	-f "$DIR/Dockerfile.deps" \
	"$DIR"

if [ -r "$DIR/Dockerfile${OPT_JENKINS:+.jenkins}" ]; then
	[ "${OPT_JENKINS:-}" ] && BNAME=jenkins || BNAME=FreeRADIUS
	echo Building $OSNAME $BNAME image
	docker build \
		${OPT_NOCACHE:+--no-cache} \
		${OPT_CC:+--build-arg=cc=$OPT_CC} \
		${OPT_DEV:+--build-arg=dh_key_size=128} \
		${OPT_BRANCH:+--build-arg=branch=$OPT_BRANCH} \
		-t freeradius/$OSNAME${OPT_JENKINS:+-jenkins} \
		-f "$DIR/Dockerfile${OPT_JENKINS:+.jenkins}" \
		"$DIR"
fi

exit 0
